<?php
/**
 *
 * Author: lirong
 * Date: 2017/11/19
 * Time: 22:07
 */

define('APP_ROOT',str_replace("\\",'/',__DIR__.'/'));

class Job{

    private  $_beanstalkd =null;

    public function __construct(){
        include APP_ROOT.'Config/conf.php';
        include APP_ROOT.'Beanstalkd/Beanstalkd.php';
        $this->_beanstalkd =new Beanstalkd($config);
    }


    public function start(){

        if (!$this->_beanstalkd->connect()){
            exit("beanstalk is not connnect");
        }
        $this->_beanstalkd->useTube("trj_orders_pay_check");
        $this->_beanstalkd->watch("trj_orders_pay_check");
        $i=1;
        while (true){
            $job =$this->_beanstalkd->reserve();
            $result =$this->dojob($job);
            if ($result){
                 $res = $this->_beanstalkd->delete($job['id']);
                 if ($res){
                     echo $i."---".$job['id']."--success".PHP_EOL;
                 }else{
                     echo $i."---".$job['id']."-- error ".PHP_EOL;
                 }
            }
            $file =APP_ROOT."shutdown.txt";
            if (file_exists($file)){
                file_put_contents($file,"beanstalk在".date("Y-m-d H:i:s")."关闭");
                break;
            }
            $i++;
        }
        $this->_beanstalkd->disconnect();
    }

    public function dojob($job){
        if (empty($job)){
            file_put_contents(APP_ROOT."/shutdown.txt",date("Y-m-d H:i:s")."关闭");
            return false;
        }
        $jobid =$job['id'];
        $jobbody =unserialize($job['body']);
        $arr =unserialize($jobbody['args']['val']);
        $string ="[".$jobid."]--订单号： ". $arr['s_no']."           pay_type:  ".$arr['pay_type']."       status:  ".$arr['status']."       ".date('Y-m-d H:i:s').PHP_EOL;
        file_put_contents(APP_ROOT."/job_".date('m_d_H').".log",$string,FILE_APPEND);
        return true;
    }

}

$jobQuene =new Job();
$jobQuene->start();